package com.rock.code.common.interceptors;


import com.rock.code.base.domain.Constants;
import com.rock.code.common.annotations.ValidateLogin;
import com.rock.code.common.spring.SpringControllerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: zhangdajun
 * Date: 14-5-28
 * Time: 下午9:37
 * To change this template use File | Settings | File Templates.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private final static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    /**
     * Handler执行完成之后调用这个方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exc) throws Exception {

    }

    /**
     * Handler执行之后，ModelAndView返回之前调用这个方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * Handler执行之前调用这个方法
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof SockJsHttpRequestHandler) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod method = (HandlerMethod) handler;
        Object userObj = request.getSession().getAttribute(Constants.SESSION_USER);
        if (userObj != null) {
            // 向上下文中注入request、response
            try {
                SpringControllerContext.getContext().setRequest(request);
                SpringControllerContext.getContext().setResponse(response);
                return super.preHandle(request, response, handler);
            } catch (Exception ex) {
                ex.printStackTrace();
                return false;
            }
        } else {
            // 使用Auth注解校验方法是否需要通过登录才可访问
            ValidateLogin validate = method.getMethod().getAnnotation(ValidateLogin.class);
            // 验证登陆超时问题  auth = null，默认验证
            if (validate != null && !validate.verifyLogin()) {
                SpringControllerContext.getContext().setRequest(request);
                SpringControllerContext.getContext().setResponse(response);
                return super.preHandle(request, response, handler);
            } else {
                // Ajax 请求处理
                if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType("text/html");
                    response.setDateHeader("Expires", 0);
                    response.setHeader("sessionstatus", "timeout");
                    return false;
                } else { // Http 请求处理
                    String baseUri = request.getContextPath();
                    //不符合条件的，跳转到登录界面
                    response.sendRedirect(baseUri + "/login");
                    return false;
                }
            }
        }
    }
}
